package com.yumeko.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yumeko.entity.TPayment;
import com.yumeko.service.PaymentService;
import com.yumeko.utils.ResponseData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @program: cloud-consumer-order90
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-17 20:49
 */
@RestController
public class CircleBreakerController {

    @Value("${service-url.nacos-user-service}")
    public String serverUrl;

    //ribbon系列调用
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback")//无配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") //系统级别的
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler")//sentinel 级别的
    //@SentinelResource(value = "fallback", fallback = "handlerFallback",blockHandler = "blockHandler")
    //@SentinelResource(value = "fallback", fallback = "handlerFallback",blockHandler = "blockHandler",exceptionsToIgnore = {IllegalArgumentException.class}) // 排除
    public ResponseData<TPayment> fallback(@PathVariable("id") Long id) {

        ResponseData<TPayment> result = restTemplate.getForObject(serverUrl + "/paymentSQL/" + id, ResponseData.class, id);

        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException,该ID没有对应记录，空指针异常");
        }
        return result;
    }

    public ResponseData handlerFallback(@PathVariable("id") Long id, Throwable e) {
        TPayment payment = new TPayment(id, "null");
        return new ResponseData(444, "兜底异常handlerFallback，exception内容" + e.getMessage(), payment);
    }

    public ResponseData blockHandler(@PathVariable("id") Long id, BlockException blockException) {
        TPayment payment = new TPayment(id, "null");
        return new ResponseData(445, "blockHandler-sentinel限流，无此流水：blockException" + blockException.getClass().getCanonicalName(), payment);
    }

    //openfeign 系列调用
    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/paymentSQL/{id}")
    public ResponseData<TPayment> paymentSQL(@PathVariable("id") Long id) {
        return paymentService.PaymentSQL(id);
    }
}
